package co.edu.unal.satacredito.database.administration.ejb;

import java.net.UnknownHostException;
import java.util.List;
import javax.ejb.Stateless;
import org.bson.types.ObjectId;
import co.edu.unal.satacredito.database.administration.exceptions.DAOException;
import co.edu.unal.satacredito.database.administration.singleton.SingletonDataStore;
import co.edu.unal.satacredito.database.connection.EstablishmentDatastoreFactory;
import co.edu.unal.satacredito.database.dao.EstablishmentMongoDao;
import co.edu.unal.satacredito.database.dao.FileLogMongoDao;
import co.edu.unal.satacredito.database.entity.Establishment;
import co.edu.unal.satacredito.database.entity.exceptions.NonexistentEntityException;
import co.edu.unal.satacredito.database.entity.exceptions.PreexistingEntityException;

import com.mongodb.MongoException;

/**
 * Session Bean implementation class EstablishmentDaoEJB
 */
@Stateless
public class EstablishmentDaoEJB implements EstablishmentDaoEJBLocal, EstablishmentDaoEJBRemote {

	private EstablishmentMongoDao daoE;

	/**
	 * Default constructor.
	 * 
	 * @throws DAOException
	 */
	public EstablishmentDaoEJB() throws DAOException {
		this.daoE = new EstablishmentMongoDao(SingletonDataStore.getInstance()
				.getDataStore());
	}

	@Override
	public void createEstablishment(Establishment establishment) throws DAOException {
		try {
			daoE.create(establishment);
		} catch (PreexistingEntityException e) {
			throw new DAOException(e.getMessage());
		}	
	}

	@Override
	public void editEstablishment(String id, Establishment establishment) throws DAOException {
		try {
			//daoE.update(establishment.getId(), establishment);
			daoE.delete(new ObjectId(id));
			daoE.create(establishment);
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}	
	}

	@Override
	public void deleteEstablishment(String id) throws DAOException {
		try {
			daoE.delete(new ObjectId(id));
		} catch (NonexistentEntityException e) {
			throw new DAOException(e.getMessage());
		}
	}
	
	@Override
	public List<Establishment> findAllEstablishment() throws DAOException {
		try {
			List<Establishment> list = daoE.findAll();
			return list;
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}
	}
	
	@Override
	public Establishment findEstablishmentById(String id) throws DAOException {
		try {
			return daoE.findById(new ObjectId(id));
		} catch (Exception e) {
			throw new DAOException(e.getMessage());
		}
	}

}
